package cn.iocoder.yudao.module.chat.service.gpt;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.module.chat.dal.dataobject.gpt.GPTTemplateDO;
import cn.iocoder.yudao.module.chat.enums.ErrorCodeConstants;
import cn.iocoder.yudao.module.chat.service.template.GPTTemplateService;
import com.unfbx.chatgpt.OpenAiStreamClient;
import com.unfbx.chatgpt.entity.chat.ChatCompletion;
import com.unfbx.chatgpt.entity.chat.Message;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;

@Service
@Slf4j
public class GPTServiceImpl implements GPTService{

    @Resource
    private GPTTemplateService gPTTemplateService;

    @Resource
    private OpenAiStreamClient openAiStreamClient;
    @Override
    public void getStreamResponse(String sessionId, String content) {

    }

    @Override
    public boolean registerSession(String sessionId, Long templateId) {
        List<Message> messages = gPTTemplateService.findGPTTemplateById(templateId);
        //聊天模型：gpt-3.5
        ChatCompletion chatCompletion = ChatCompletion.builder().user(sessionId).messages(messages).build();
        openAiStreamClient.streamChatCompletion(chatCompletion, new EventSourceListener() {
            @Override
            public void onEvent(@NotNull EventSource eventSource, @Nullable String id, @Nullable String type, @NotNull String data) {
                if (data.equals("[DONE]")) {
                    log.info("OpenAI返回数据结束了");
                }
//                ObjectMapper mapper = new ObjectMapper();
//                ChatCompletionResponse completionResponse = mapper.readValue(data, ChatCompletionResponse.class); // 读取Json
//                String delta = mapper.writeValueAsString(completionResponse.getChoices().get(0).getDelta());
            }
        });
        return false;
    }


    private boolean checkFormats(String templateContent){
        return JSONUtil.isTypeJSONArray(templateContent);
    }
}
